﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SECSendMsgService
{
    public partial class SECSendMsgService : ServiceBase
    {
        //发送信息的配置
        SendMsgConfig cg;
        //服务停止开关
        bool blStop = false;

        public SECSendMsgService()
        {
            //服务必须的
            InitializeComponent();
            File.AppendAllText("c:/1.txt", "开始读取配置文件!/r/n");
            string path = AppDomain.CurrentDomain.BaseDirectory + "MsgConfig.xml";
            cg = new SendMsgConfig(path);
            File.AppendAllText("c:/1.txt", "配置文件读取完毕!/r/n");
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务 
            EventLog.WriteEntry("发信息服务启动!1123");
            File.AppendAllText("c:/1.txt", "发邮件 服务启动!/r/n");
            blStop = false;
            Thread msgThread = new Thread(new ThreadStart(SendMsgRun));
            msgThread.Start();
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作 
            EventLog.WriteEntry("发信息 服务停止!");
            File.AppendAllText("c:/1.txt", "发邮件 服务停止!/r/n");
            blStop = true;
        }

        /// <summary>
        /// 发送邮件前的判断
        /// </summary>
        private void SendMsgRun()
        {
            File.AppendAllText("c:/1.txt", "SendMsgRun了!/r/n");
            //发送信息         
            bool blExecute = false;
            while (!blStop)//如果服务开启
            {
                string strSysTime = DateTime.Now.ToString("yyyyMMdd HH:mm");//得到当前时间
                #region 设置时间间隔
                //判断是否时间与设定的时间相同
                foreach (string strTime in cg.TimeList)//cg邮件的配置类
                {
                    //如果最后一次时间和当前时间不同并且当前时间和列表中的时间相同的话开始发送邮件
                    if (!(string.Equals(strSysTime, cg.LastDateTime)) && string.Equals(strSysTime, DateTime.Now.ToString("yyyyMMdd") + " " + strTime))
                    {
                        blExecute = true;
                        break;
                    }
                }
                if (blExecute)//时间匹配
                {
                    //保存上一次执行时间
                    cg.LastDateTime = strSysTime;
                    blExecute = false;//初始化发送条件                   
                    SendMsg();//发送邮件
                }
                #endregion
                else//不匹配休眠一分钟
                {
                    System.Threading.Thread.Sleep(60000);
                }
            }
        }
        /// <summary>
        /// 去数据库找出待发送邮件
        /// </summary>
        public void SendMsg()
        {

            using(MsgDataContext db=new MsgDataContext(GetCS()))
            {
                try
                {
                    //输出连接字符串
                    File.AppendAllText("c:/1.txt",GetCS());
                    //找到待发送的信息
                    List<SMSApplyRecords> sars =
                        (from m in db.SMSApplyRecords
                        where m.SendFlag == 2
                        select m).ToList();
                    if (sars.Count > 0)//有数据的话发送
                    {
                        //循环发送
                        foreach (var item in sars)
                        {
                            //判断发送时间是否比现在的时间小
                            if (item.SendTime < DateTime.Now)
                            {
                                //
                                if (Send(cg.UserName, cg.Password, item.Message, item.Mobile))
                                {
                                    File.AppendAllText("c:/1.txt", "ok了");
                                }
                            }
                        }
                       
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry("连接数据库异常:"+ex.Message);
                    File.AppendAllText("c:/1.txt","连接数据库异常:" + ex.Message);
                }

            }
        }

        #region 得到连接数据库的字符串
        private string GetCS()
        {
            string strcs = System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
            string[] ListCS = strcs.Split(';');
            string connectionstring = string.Empty;
            string key = System.Configuration.ConfigurationManager.AppSettings["key"];//字符串解密钥匙
            MySecurity ms = new MySecurity(key);//字符串解密类
            foreach (var item in ListCS)
            {
                string str = item;

                if (!string.IsNullOrEmpty(str))
                {
                    string TopStr = str.Substring(0, str.IndexOf("=")).Trim().ToLower();
                    if (TopStr.Equals("password") || TopStr.Equals("pwd"))
                    {
                        str = str.Replace(str.Substring(item.IndexOf("=") + 1), ms.DecryptString(str.Substring(item.IndexOf("=") + 1)));
                    }
                    connectionstring = connectionstring + str + ";";
                }
            }

            return connectionstring;
        }
        #endregion

        #region 接口发送信息
        /// <summary>
        /// 接口发送信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="message">发送的信息</param>
        /// <param name="mobileList">收件人的集合;分割</param>
        /// <returns></returns>
        public bool Send(string userName, string password, string message, string mobileList)
        {
            return true;
        } 
        #endregion

    }
}
